package com.example.controller;

import com.example.common.Result;
import com.example.entity.ChatMessage;
import com.example.service.AiChatService;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;

import java.util.List;
import java.util.Map;

/**
 * AI聊天接口
 */
@RestController
@RequestMapping("/ai/chat")
public class AiChatController {

    @Resource
    private AiChatService aiChatService;

    /**
     * 发送消息给AI
     */
    @PostMapping("/send")
    public Result sendMessage(@RequestBody Map<String, String> params) {
        try {
            String userMessage = params.get("message");
            if (userMessage == null || userMessage.trim().isEmpty()) {
                return Result.error("400", "消息不能为空");
            }
            String aiResponse = aiChatService.chat(userMessage);
            return Result.success(aiResponse);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("500", "AI服务异常：" + e.getMessage());
        }
    }

    /**
     * 获取聊天历史
     */
    @GetMapping("/history")
    public Result getChatHistory(@RequestParam(defaultValue = "20") Integer limit) {
        try {
            Integer userId = TokenUtils.getCurrentUser().getId();
            List<ChatMessage> history = aiChatService.getChatHistory(userId, limit);
            return Result.success(history);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("500", "获取聊天历史失败：" + e.getMessage());
        }
    }

    /**
     * 清空聊天历史
     */
    @DeleteMapping("/history/clear")
    public Result clearHistory() {
        try {
            Integer userId = TokenUtils.getCurrentUser().getId();
            aiChatService.clearHistory(userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("500", "清空聊天历史失败：" + e.getMessage());
        }
    }

    /**
     * 新增（管理用）
     */
    @PostMapping("/add")
    public Result add(@RequestBody ChatMessage chatMessage) {
        aiChatService.add(chatMessage);
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        aiChatService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     */
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        aiChatService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public Result updateById(@RequestBody ChatMessage chatMessage) {
        aiChatService.updateById(chatMessage);
        return Result.success();
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        ChatMessage chatMessage = aiChatService.selectById(id);
        return Result.success(chatMessage);
    }

    /**
     * 查询所有
     */
    @GetMapping("/selectAll")
    public Result selectAll(ChatMessage chatMessage) {
        List<ChatMessage> list = aiChatService.selectAll(chatMessage);
        return Result.success(list);
    }

    /**
     * 分页查询
     */
    @GetMapping("/selectPage")
    public Result selectPage(ChatMessage chatMessage,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<ChatMessage> page = aiChatService.selectPage(chatMessage, pageNum, pageSize);
        return Result.success(page);
    }
}

